package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eightbears.beboy.MainActivity;
import com.eightbears.beboy.R;
import com.eightbears.beboy.SplashActivity;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.util.ClearCacheManager;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.base.view.dialog.EditDataDialog;
import com.eightbears.beboy.base.view.dialog.SexDialog;
import com.eightbears.beboy.base.view.image.circle.ClipImageActivity;
import com.eightbears.beboy.base.view.picker.AddressPickTask;
import com.eightbears.beboy.base.view.picker.DatePicker;
import com.eightbears.beboy.base.view.picker.entity.City;
import com.eightbears.beboy.base.view.picker.entity.County;
import com.eightbears.beboy.base.view.picker.entity.Province;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.base.view.popupwindow.MultipeSelectionPopup;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.WeiChatEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.DemoHelper;
import com.eightbears.beboy.ui.chat.base.PreferenceManager;
import com.eightbears.beboy.ui.login.ForgetActivity;
import com.eightbears.greendao.District;
import com.makeramen.roundedimageview.RoundedImageView;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.wechat.Wechat;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CACHE_FILE;
import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_USER_DATA;
import static com.eightbears.beboy.ui.user.activity.TransferActivity.PARAMS_PAY_TRANSFER;
import static com.eightbears.beboy.ui.user.fragment.MyFragment.EVENT_UPDATE_USERINFO;

public class SettingActivity extends BaseActivity {

    public static final String EVENT_USER_HEAD_UPDATE = "userHeadUpdate";
    public static final String EVENT_EXIT = "exit";
    public static final String EVENT_FINISH = "finish";


    // 头像
    private static final int REQUEST_CAPTURE = 100;        //请求相机
    private static final int REQUEST_PICK = 101;          //请求相册
    private static final int REQUEST_CROP_PHOTO = 102;    //请求截图
    private File tempFile;                                //调用照相机返回图片文件
    private String cropImagePath;                         // 剪裁路径


    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.iv_user_head)
    RoundedImageView iv_user_head;
    @BindView(R.id.tv_user_nickname)
    TextView tv_user_nickname;
    @BindView(R.id.tv_user_sex)
    TextView tv_user_sex;
    @BindView(R.id.tv_user_birthday)
    TextView tv_user_birthday;
    @BindView(R.id.tv_setting_address_text)
    TextView tv_setting_address_text;
    @BindView(R.id.tv_user_weixin)
    TextView tv_user_weixin;
    @BindView(R.id.rl_setting_weixin)
    RelativeLayout rl_setting_weixin;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_memory)
    TextView tv_memory;

    private String selectYear;
    private String selectMonth;
    private String selectDay;

    private WeiChatEntity weiChatEntity;
    private String updateBir;
    private UserEntity oldUser;
    private String districtName;
    private String cityName;
    private String provinceName;
    private String mBirthday;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_setting);
    }

    @Override
    protected void initData() {
        oldUser = SPUtil.getUser();
        initAddress();
        CommonUtils.loadImageView(SettingActivity.this, oldUser.getData().getCover(),
                R.mipmap.default_head, iv_user_head);
        tv_user_nickname.setText(oldUser.getData().getNickname());
        if (oldUser.getData().getSex().equals("1")) {
            tv_user_sex.setText(getString(R.string.text_man));
        } else if (oldUser.getData().getSex().equals("2")) {
            tv_user_sex.setText(getString(R.string.text_women));
        }
        mBirthday = oldUser.getData().getBirthday();
        initBirthdayData();
        tv_user_birthday.setText(mBirthday);
        String wechatBind = oldUser.getData().getThird_party();
        if (wechatBind.equals("1")) {
            tv_user_weixin.setText(getString(R.string.text_wechat_bind));
            rl_setting_weixin.setEnabled(false);
        } else {
            tv_user_weixin.setText(getString(R.string.text_wechat_no_bind));
        }
        getCacheDataSize();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    public void initAddress() {
        oldUser = SPUtil.getUser();
        String myAddress;
        if (!TextUtils.isEmpty(oldUser.getData().getDistrict_id())) {
            District district = DistrictCache.getInstance(this).getCacheById(oldUser.getData().getDistrict_id());
            if (district != null) {
                District city = DistrictCache.getInstance(this).getCacheById(district.getParent_id());
                District province = DistrictCache.getInstance(this).getCacheById(city.getParent_id());
                districtName = district.getName();
                cityName = city.getName();
                provinceName = province.getName();
                if (provinceName.contains(getString(R.string.text_district_province))) {
                    provinceName = provinceName.replace(getString(R.string.text_district_province), " ");
                }
                myAddress = provinceName + " " + cityName + " " + districtName;
            } else {
                provinceName = "广东";
                cityName = "广州";
                districtName = "天河";
                myAddress = getString(R.string.text_please_address);
            }
        } else {
            provinceName = "广东";
            cityName = "广州";
            districtName = "天河";
            myAddress = getString(R.string.text_please_address);
        }

        tv_setting_address_text.setText(myAddress);
    }

    @OnClick(R.id.rl_setting_head)
    void updateHead() {
        showImageDialog();
    }

    @OnClick(R.id.rl_setting_nickname)
    void updateNickName() {
        final EditDataDialog editDataDialog = new EditDataDialog(this);
        editDataDialog.setTitleText(getString(R.string.text_edit_nickname));
        editDataDialog.setEditHintText(getString(R.string.hide_nickname));
        editDataDialog.show();
        editDataDialog.setOnItemClickListener(new EditDataDialog.DialogEditNameListener() {
            @Override
            public void onSetDialogNumOneListener(View v, String name) {
                switch (v.getId()) {
                    case R.id.btn_cancel:
                        editDataDialog.dismiss();
                        break;
                    case R.id.btn_editdialog_ensure:
                        if (!TextUtils.isEmpty(name)) {
                            if (name.equals(oldUser.getData().getNickname())) {
                                ShowToast.showShortToast(getString(R.string.text_nick_exist));
                                return;
                            }
                            postUserName(name);//上存网络
                            editDataDialog.dismiss();
                        } else {
                            ShowToast.showShortToast(R.string.alert_input_empty);
                        }
                        break;
                }
            }
        });
        editDataDialog.setCancelable(true);
        editDataDialog.setCanceledOnTouchOutside(true);
    }

    @OnClick(R.id.rl_setting_sex)
    void updateSex() {
        final SexDialog sexDialog = new SexDialog(mContext);
        sexDialog.show();
        sexDialog.setOnItemClickListener(new SexDialog.onDialogItemClickListener() {
            int numSex = 0;

            @Override
            public void onItemClick(String s) {
                if (s.equals("男")) {
                    numSex = 1;
                    sexDialog.dismiss();
                } else if (s.equals("女")) {
                    numSex = 2;
                    sexDialog.dismiss();
                }
                postUserSex(numSex);//上存
            }
        });
        sexDialog.setCancelable(true);
        sexDialog.setCanceledOnTouchOutside(true);
    }

    //TODO
    @OnClick(R.id.rl_setting_birthday)
    void updateBirthday() {
        final DatePicker picker = new DatePicker(this);
        picker.setUseWeight(true);
        picker.setCanceledOnTouchOutside(true);
        picker.setRangeStart(1900, 1, 1);
        picker.setRangeEnd(2111, 1, 1);
        picker.setSelectedItem(Integer.parseInt(selectYear), Integer.parseInt(selectMonth), Integer.parseInt(selectDay));
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                updateBir = year + "-" + month + "-" + day;
                selectYear = year;
                selectMonth = month;
                selectDay = day;
                postUserDate();
            }
        });
        picker.show();
    }

    @OnClick(R.id.rl_setting_setaddress)
    void setAddress() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                postUserAddress(county.getAreaId());
            }

            @Override
            public void onAddressInitFailed() {
                ShowToast.showShortToast(getString(R.string.error_init_data));
            }

        });
        task.execute(provinceName, cityName, districtName);
    }

    @OnClick(R.id.rl_setting_password)
    void updatePassword() {
        startLocalActivity(this, ForgetActivity.class);
    }

    @OnClick(R.id.rl_setting_pay_password)
    void pay_password() {
        startLocalActivity((Activity) mContext, ForgetActivity.class, PARAMS_PAY_TRANSFER, PARAMS_PAY_TRANSFER);
    }

    @OnClick(R.id.rl_setting_weixin)
    void wechatBind() {
        view_loading.setVisibility(View.VISIBLE);
        wxLogin();
    }

    @OnClick(R.id.rl_setting_address)
    void shoppingAddress() {
        startLocalActivity(this, ShoppingAddressActivity.class);
    }

    @OnClick(R.id.rl_setting_clear)
    void clearCache() {
        if (ClearCacheManager.getFolderSize(new File(CACHE_FILE)) == 0) {
            ShowToast.showShortToast(getString(R.string.alert_no_clear_cache));
            return;
        }
        DefaultDialog.Builder builder = new DefaultDialog.Builder(this);
        builder.setTitle(R.string.alert_text);
        builder.setMessage(getString(R.string.alert_text_clear_cache));
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ClearCacheManager.deleteAllFile(new File(CommonAPI.CACHE_FILE));
                getCacheDataSize();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @OnClick(R.id.rl_feedback)
    void feedback() {
        startLocalActivity(this, FeedbackActivity.class);
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    private MultipeSelectionPopup multipeSelectionPopup;


    @OnClick(R.id.rl_exit)
    void exit() {
        if (multipeSelectionPopup == null) {
            multipeSelectionPopup = new MultipeSelectionPopup((Activity) mContext);
            multipeSelectionPopup.setTx_title(getString(R.string.text_exit));
            multipeSelectionPopup.setTx_1Text(getString(R.string.text_login_out));
            multipeSelectionPopup.setTx_2Text(getString(R.string.text_close_app));
            multipeSelectionPopup.setOnClickItemListener(new MultipeSelectionPopup.OnClicktemListener() {
                @Override
                public void onClickItem(View v) {
                    switch (v.getId()) {
                        case R.id.ll_1:
//                            exitApp();
                            multipeSelectionPopup.dismiss();
                            finish();
                            EventBus.getDefault().post(EVENT_EXIT);
                            break;
                        case R.id.ll_2:
                            multipeSelectionPopup.dismiss();
                            finish();
                            EventBus.getDefault().post(EVENT_FINISH);
                            break;
                    }
                }
            });
        }
        multipeSelectionPopup.showPopupWindow();
    }


    private void showImageDialog() {
        BottomSelectionPopup bottomSelectionPopup = new BottomSelectionPopup(SettingActivity.this);
        bottomSelectionPopup.setTxCancel(getResources().getString(R.string.btn_cancel));
        bottomSelectionPopup.setTx_1Text(getResources().getString(R.string.text_select_image));
        bottomSelectionPopup.setTx_2Text(getResources().getString(R.string.text_select_capture));
        bottomSelectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        selectPicture();
                        break;
                    case R.id.ll_2:
                        getCapture();
                        break;
                }
            }
        });
        bottomSelectionPopup.showPopupWindow();
    }

    private void selectPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    private void getCapture() {
        //创建拍照存储的图片文件
        tempFile = new File(checkDirPath(CommonAPI.CACHE_HEAD_FILE), System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    /**
     * 根据Uri返回文件绝对路径, file:///开头的 和 content://开头的情况
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }

    private void getCacheDataSize() {
        long memorySize = ClearCacheManager.getFolderSize(new File(CommonAPI.CACHE_FILE));
        Double temNum = (double) memorySize;
        String formatSize = ClearCacheManager.getFormatSize(temNum);
        tv_memory.setText(formatSize);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CAPTURE:
                if (resultCode == RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:
                if (null != data) {
                    Uri pickUri = data.getData();
                    gotoClipActivity(pickUri);
                }
                break;
            case REQUEST_CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri cropUri = data.getData();
                    if (cropUri == null) {
                        return;
                    }
                    cropImagePath = getRealFilePathFromUri(getApplicationContext(), cropUri);
                    postUserImage();
                }
                break;
        }
    }

    /**
     * 修改图片
     */
    public void postUserImage() {
        OkHttpUtils.post().url(URL_USER_DATA)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addFile("cover", "cover", new File(cropImagePath))
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    oldUser.getData().setCover(userEntity.getData().getCover());
                    SPUtil.putUser(oldUser);
                    CommonUtils.loadImageView(SettingActivity.this, oldUser.getData().getCover(),
                            R.mipmap.default_head, iv_user_head);
                    PreferenceManager.getInstance().setCurrentUserAvatar(oldUser.getData().getCover());
                    EventBus.getDefault().post(EVENT_USER_HEAD_UPDATE);
                    tv_user_nickname.setText(oldUser.getData().getNickname());
                    ShowToast.showShortToast(getString(R.string.alert_update_success));
                    EventBus.getDefault().post(EVENT_UPDATE_USERINFO);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SettingActivity.this, status_error);
            }
        });
    }

    /**
     * 修改昵称
     */
    public void postUserName(String name) {

        OkHttpUtils.post().url(URL_USER_DATA)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("nickname", name)
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    oldUser.getData().setNickname(userEntity.getData().getNickname());
                    SPUtil.putUser(oldUser);
//                    PreferenceManager.getInstance().setCurrentUserNick(oldUser.getData().getNickname());
                    ShowToast.showShortToast(getString(R.string.alert_update_success));
                    tv_user_nickname.setText(userEntity.getData().getNickname());
                    EventBus.getDefault().post(EVENT_UPDATE_USERINFO);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SettingActivity.this, status_error);
            }
        });
    }

    /**
     * 修改性别
     */
    public void postUserSex(int sex) {
        OkHttpUtils.post().url(URL_USER_DATA)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("sex", sex + "")
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    oldUser.getData().setSex(userEntity.getData().getSex());
                    if (userEntity.getData().getSex().equals("1")) {
                        tv_user_sex.setText(getString(R.string.text_man));
                    } else if (userEntity.getData().getSex().equals("2")) {
                        tv_user_sex.setText(getString(R.string.text_women));
                    }
                    SPUtil.putUser(oldUser);
                    ShowToast.showShortToast(getString(R.string.alert_update_success));
                    EventBus.getDefault().post(EVENT_UPDATE_USERINFO);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SettingActivity.this, status_error);
            }
        });
    }

    /**
     * 日期
     */
    public void postUserDate() {
        OkHttpUtils.post().url(URL_USER_DATA)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("birthday", updateBir)
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    oldUser.getData().setBirthday(userEntity.getData().getBirthday());
                    SPUtil.putUser(oldUser);
                    tv_user_birthday.setText(oldUser.getData().getBirthday());
                    ShowToast.showShortToast(getString(R.string.alert_update_success));
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SettingActivity.this, status_error);
            }
        });

    }

    /**
     * 修改地址
     */
    public void postUserAddress(String disId) {

        OkHttpUtils.post().url(URL_USER_DATA)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("district_id", disId)
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    oldUser.getData().setDistrict_id(userEntity.getData().getDistrict_id());
                    SPUtil.putUser(oldUser);
                    initAddress();
                    ShowToast.showShortToast(getString(R.string.alert_update_success));
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SettingActivity.this, status_error);
            }
        });
    }

    // 微信登录
    public void wxLogin() {
        JShareInterface.authorize(Wechat.Name, mAuthListener);
    }

    /**
     * 上传微信
     */
    public void postUserWeiXin() {

        OkHttpUtils.post().url(URL_USER_DATA)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("open_id", SPUtil.getWChat().getOpenid())
                .addParams("access_token", SPUtil.getWChat().getAccess_token())
                .build().execute(new StringCallback() {
            @Override

            public void onResponse(String response) {
                view_loading.setVisibility(View.GONE);
                UserEntity userEntity = GsonUtil.fromJson(response, UserEntity.class);
                if (userEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    oldUser.getData().setThird_party(userEntity.getData().getThird_party());
                    SPUtil.putUser(oldUser);
                    ShowToast.showShortToast(getString(R.string.alert_update_success));
                    tv_user_weixin.setText(getString(R.string.text_wechat_bind));
                    rl_setting_weixin.setEnabled(false);
                    view_loading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                view_loading.setVisibility(View.GONE);
                ShowToast.showShortToast(getString(R.string.text_update_head_error));
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SettingActivity.this, status_error);
            }
        });
    }


    AuthListener mAuthListener = new AuthListener() {
        @Override
        public void onComplete(Platform platform, int action, BaseResponseInfo data) {
            WeiChatEntity weiChatEntity = new WeiChatEntity();
            weiChatEntity.setAccess_token(((AccessTokenInfo) data).getToken());
            weiChatEntity.setRefresh_token(((AccessTokenInfo) data).getRefeshToken());
            weiChatEntity.setOpenid(((AccessTokenInfo) data).getOpenid());
            SPUtil.putWChat(weiChatEntity);
            postUserWeiXin();
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            view_loading.setVisibility(View.GONE);
        }

        @Override
        public void onCancel(Platform platform, int action) {
            ShowToast.showShortToast(getString(R.string.alert_cancel_wchat_login));
            view_loading.setVisibility(View.GONE);
        }
    };

    //退出登录
    private void exitApp() {
        new MainActivity().unregisterBroadcastReceiver();
        DemoHelper.getInstance().logout(true, null);
        SPUtil.loginOut();
        startLocalActivityAndClear((Activity) mContext, SplashActivity.class);
    }

    private void initBirthdayData() {
        String[] data = mBirthday.split("-");
        for (int i = 0; i < data.length; i++) {
            if (i == 0) selectYear = data[0];
            if (i == 1) selectMonth = data[1];
            if (i == 2) selectDay = data[2];
        }
    }
}